<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData" v-on:appTreeClick="appTreeClick"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              姓名：<el-input placeholder="请输入内容" v-model="selectForm.name" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              性别：
              <el-select v-model="selectForm.gender" clearable placeholder="请选择">
                <el-option v-for="(item,index) in genderOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              出生年月：
              <el-date-picker
                v-model="selectForm.birthday"
                :picker-options="dataPickerBeforeTodayOptions"
                value-format="yyyyMMdd"
                format="yyyy 年 MM 月 dd 日"
                placeholder="选择日期时间">
              </el-date-picker>
            </div>
            <div>
              学校：
              <el-select v-model="selectForm.schoolId" clearable filterable placeholder="请选择">
                <el-option v-for="(school,index) in schoolOption" :key="index" :label="school.schoolName" :value="school.id"></el-option>
              </el-select>
            </div>
            <div>
              危害程度：
              <el-select v-model="selectForm.dangerDegree" clearable filterable placeholder="请选择">
                <el-option v-for="(item,index) in dangerOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              是否关注：
              <el-select v-model="selectForm.hasFollow" clearable placeholder="请选择">
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows">
          </app-table>
          <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogFormVisible"
            :before-close="cancel"
            :close-on-click-modal="false"
            class="custom-dialog_style">
            <el-form :model="formData" :rules="rules" :disabled="showOnly" ref="formData">
              <el-form-item label="公民身份号码：" prop="identityNumber">
                <el-input v-model="formData.identityNumber" autocomplete="off" @blur="identityNumberHaveDone(formData.identityNumber)"></el-input>
              </el-form-item>
              <el-form-item label="姓名：" prop="name">
                <el-input v-model="formData.name" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="曾用名：">
                <el-input v-model="formData.usedName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="性别：" prop="gender">
                <el-select v-model="formData.gender" clearable placeholder="请选择">
                  <el-option v-for="(item,index) in genderOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="出生日期：" prop="birthday">
                <el-date-picker
                  v-model="formData.birthday"
                  :picker-options="dataPickerBeforeTodayOptions"
                  value-format="yyyyMMdd"
                  format="yyyy 年 MM 月 dd 日"
                  placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="民族：" prop="nation">
                <el-select v-model="formData.nation" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in nationOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="籍贯：">
                <el-input v-model="formData.birthplace" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="婚姻状况：">
                <div class="block">
                  <el-cascader
                    v-model="formData.maritalStatusArr"
                    placeholder="请选择"
                    :options="maritalStatusOption"
                    filterable
                    :props="dictProps"
                    clearable
                    change-on-select>
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="政治面貌：">
                <el-select v-model="formData.politicalStatus" clearable placeholder="请选择" filterable>
                  <el-option v-for="(item,index) in politicalStatusOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="学历：">
                <div class="block">
                  <el-cascader
                    v-model="formData.educationArr"
                    placeholder="请选择"
                    :options="educationOption"
                    filterable
                    :props="dictProps"
                    clearable
                    change-on-select>
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="宗教信仰：">
                <el-select v-model="formData.religion" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in religionOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="职业类别：">
                <el-select v-model="formData.careerCategory" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in careerCategoryOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="职业：">
                <el-input v-model="formData.career" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="服务处所：">
                <el-input v-model="formData.servicePlace" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="联系方式：">
                <el-input v-model="formData.phone" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="户籍地：">
                <el-input v-model="formData.householdAddr" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="户籍门(楼)详址：">
                <el-input v-model="formData.householdAddrDetail" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="现住地：">
                <el-input v-model="formData.currentAddr" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="现住门(楼)详址：">
                <el-input v-model="formData.currentAddrDetail" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="危害程度：">
                <el-select v-model="formData.dangerDegree" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in dangerOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="是否关注：">
                <el-select v-model="formData.hasFollow" clearable placeholder="请选择">
                  <el-option label="是" :value="1"></el-option>
                  <el-option label="否" :value="0"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="所属网格：" prop="gridIdArr">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="treeData"
                    :props="gridIdProps"
                    filterable
                    clearable
                    change-on-select
                    @change="gridChangEvt"
                    v-model="formData.gridIdArr">
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="所在学校：" prop="schoolId">
                <el-select v-model="formData.schoolId" clearable filterable placeholder="请选择">
                  <el-option v-for="(school,index) in schoolOption" :key="index" :label="school.schoolName" :value="school.id"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="isfooterBtnShow">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="save('formData')">确 定</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import {getAllRegion} from '@/utils/region'
import {validateIdefer} from '@/utils/validate'
import {getPopulation} from '@/http/PopulationApi'
import {getUserGridTree} from '@/utils/SessionDataUtil'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {getSchoolFocusPerson, createSchoolFocusPerson, updateSchoolFocusPerson, delSchoolFocusPerson, getSchoolList, getSchoolFocusPersonById} from '@/http/SchoolAroundApi'
export default {
  data () {
    return {
      dialogFormVisible: false,
      isfooterBtnShow: true,
      treeData: [],
      pageData: {},
      dialogTitle: '',
      currentSelectedData: [],
      showOnly: false,
      tableColumns: [
        { prop: 'name', label: '姓名' },
        { prop: 'gender', label: '性别', formatter: this.genderFormatter },
        { prop: 'birthday', label: '出生日期', formatter: this.dateFormatter },
        { prop: 'nation', label: '民族', formatter: this.nationFormatter },
        { prop: 'schoolId', label: '学校', formatter: this.schoolFormatter },
        { prop: 'dangerDegree', label: '危害程度', formatter: this.dangerDegreeFormatter },
        { prop: 'hasFollow', label: '是否关注', formatter: this.hasFollowFormatter }
      ],
      tableDada: [],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      selectForm: {},
      formData: {},
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      dictProps: {
        label: 'name',
        value: 'code'
      },
      rules: {
        identityNumber: [
          { validator: validateIdefer, required: true, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        birthday: [
          { required: true, message: '请选择出生年月', trigger: 'blur' }
        ],
        nation: [
          { required: true, message: '请选择民族', trigger: 'blur' }
        ],
        schoolId: [
          { required: true, message: '请输入学校ID', trigger: 'blur' }
        ],
        gridIdArr: [
          { required: true, message: '请选择所属网格', trigger: 'blur' }
        ]
      },
      genderOption: [],
      nationOption: [],
      maritalStatusOption: [],
      politicalStatusOption: [],
      educationOption: [],
      religionOption: [],
      careerCategoryOption: [],
      dangerOption: [],
      schoolOption: []
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable
  },
  mounted () {
    this.genderOption = getDictDataOption('性别')
    this.dangerOption = getDictDataOption('危害程度')
    this.getTreeData()
    this.getTableData()
    this.getSchoolData()
  },
  methods: {
    identityNumberHaveDone (value) {
      if (!value) {
        return ''
      } else {
        getPopulation(value).then(resp => {
          if (resp.code && resp.code === '200') {
            let id = this.formData.id ? this.formData.id : null
            for (let key in resp.data) {
              if (key === 'id') continue
              this.$set(this.formData, key, resp.data[key])
            }
            let maritalStatusArr = this.formData.maritalStatusArr = this.formData.maritalStatus !== '' && this.formData.maritalStatus !== null ? this.formData.maritalStatus.split(',') : []
            let educationArr = this.formData.educationArr = this.formData.education !== '' && this.formData.education !== null ? this.formData.education.split(',') : []
            this.$set(this.formData, 'maritalStatusArr', maritalStatusArr)
            this.$set(this.formData, 'educationArr', educationArr)
            if (id !== null) this.$set(this.formData, 'id', id)
          } else {
            return false
          }
        })
      }
    },
    // 格式化性别
    genderFormatter (row, column) {
      let genderOption = getDictDataOption('性别')
      let resGender = ''
      for (let i = 0; i < genderOption.length; i++) {
        if (genderOption[i].code === row.gender) {
          resGender = genderOption[i].name
          break
        }
      }
      return resGender
    },
    // 格式化时间戳
    dateFormatter (row, column) {
      if (row && row.birthday) {
        let time = row.birthday
        return this.$moment(time).format('YYYY-MM-DD')
      }
    },
    schoolFormatter (row, column) {
      let data = this.schoolOption
      let schoolName = ''
      for (let i = 0; i < data.length; i++) {
        if (row.schoolId === data[i].id) {
          schoolName = data[i].schoolName
          break
        } else continue
      }
      return schoolName
    },
    getSchoolData (param) {
      let m = this
      getSchoolList(param).then(resp => {
        if (resp.code && resp.code === '200') {
          m.schoolOption = resp.data
        } else {
          return false
        }
      })
    },
    gridChangEvt (val) {
      if (val && val.length > 0) {
        let index = val.length - 1
        let gridId = val[index]
        this.getSchoolData({gridId: gridId})
      }
    },
    nationFormatter (row, column) {
      let nationOption = getDictDataOption('民族')
      let resNation = ''
      for (let i = 0; i < nationOption.length; i++) {
        if (nationOption[i].code === row.nation) {
          resNation = nationOption[i].name
          break
        }
      }
      return resNation
    },
    dangerDegreeFormatter (row, column) {
      let dangerDegreeOption = getDictDataOption('危害程度')
      let dangerDegree = ''
      for (let i = 0; i < dangerDegreeOption.length; i++) {
        if (dangerDegreeOption[i].code === row.dangerDegree) {
          dangerDegree = dangerDegreeOption[i].name
          break
        }
      }
      return dangerDegree
    },
    hasFollowFormatter (row, column) {
      let hasFollow = row.hasFollow === 1 ? '是' : '否'
      return hasFollow
    },
    getTreeData () {
      let data = getUserGridTree()
      if (data && data instanceof Array) {
        this.treeData = data
      }
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$alert('请填写正确表单格式', '', {
            confirmButtonText: '确定'
          })
          return ''
        } else {
          if (this.formData.gridIdArr && this.formData.gridIdArr !== 0) {
            let index = this.formData.gridIdArr.length - 1
            let data = {}
            data.id = this.formData.gridIdArr[index]
            data.items = this.treeData
            data.isGetAllId = true
            this.formData.liveAllGridId = getAllRegion(data)
          } else {
            this.formData.liveAllGridId = ''
          }
          this.formData.maritalStatus = this.formData.maritalStatusArr ? this.formData.maritalStatusArr.join(',') : ''
          this.formData.education = this.formData.educationArr ? this.formData.educationArr.join(',') : ''
          if (this.formData.id) {
            updateSchoolFocusPerson(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: '修改失败'
                })
                return ''
              }
            })
          } else {
            createSchoolFocusPerson(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: '添加失败'
                })
                return ''
              }
            })
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            delSchoolFocusPerson(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: '删除失败'
                })
                return ''
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
    },
    getTableData (param) {
      getSchoolFocusPerson(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.pageData = resp.data
          if (this.pageData.items && this.pageData.items instanceof Array) {
            this.tableData = this.pageData.items
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
        }
      })
    },
    handleCurrentChange (val) {
      this.selectForm.offset = (val - 1) * 10
      this.getTableData(this.selectForm)
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.isfooterBtnShow = callbackData.btnType !== 'get'
        this.nationOption = getDictDataOption('民族')
        this.maritalStatusOption = getDictDataOption('婚姻状况')
        this.politicalStatusOption = getDictDataOption('政治面貌')
        this.educationOption = getDictDataOption('学历')
        this.religionOption = getDictDataOption('宗教信仰')
        this.careerCategoryOption = getDictDataOption('职业分类')
        if (callbackData.btnType === 'post') {
          this.dialogTitle = '新增'
          if (this.formData.gridIdArr) {
            let arr = this.formData.gridIdArr
            this.formData = {}
            this.$set(this.formData, 'gridIdArr', arr)
          } else {
            this.formData = {}
          }
        } else {
          this.formData = callbackData.rows[0]
          let maritalStatusArr = this.formData.maritalStatus !== '' && this.formData.maritalStatus !== null ? this.formData.maritalStatus.split(',') : []
          let educationArr = this.formData.education !== '' && this.formData.education !== null ? this.formData.education.split(',') : []
          this.$set(this.formData, 'maritalStatusArr', maritalStatusArr)
          this.$set(this.formData, 'educationArr', educationArr)
          let regionData = {}
          regionData.id = this.formData.liveGridId
          regionData.items = this.treeData
          let gridIdArr = getAllRegion(regionData)
          this.$set(this.formData, 'gridIdArr', gridIdArr)
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    handleCheckedRows (rows) {
      if (rows.length <= this.currentSelectedData.length && rows.length === 1) this.currentSelectedData = []
      if (rows && rows instanceof Array && rows.length > 0) {
        let m = this
        getSchoolFocusPersonById(rows[0].id).then(resp => {
          if (resp.code && resp.code === '200') {
            m.currentSelectedData = [resp.data]
            m.formData = resp.data
          } else {
            m.$message({
              type: 'info',
              message: resp.message
            })
            return ''
          }
        })
      } else {
        this.currentSelectedData = []
        this.formData = {}
      }
    },
    appTreeClick (data) {
      let gridData = {}
      gridData.id = data.id
      gridData.items = this.treeData
      let gridIdArr = getAllRegion(gridData)
      this.$set(this.formData, 'gridIdArr', gridIdArr)
      this.selectForm.likeAllGridId = data.id
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    },
    searchHandleClick () {
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    }
  }
}
</script>
